package com.bbyl.ui;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.bbyl.IMessage;
import com.bbyl.im.service.MsgService;
import com.github.naturs.logger.Logger;
import com.github.naturs.logger.android.adapter.AndroidLogAdapter;
import com.github.naturs.logger.android.strategy.converter.AndroidLogConverter;

public class BbylApplication extends Application {

    private static final String TAG = "BbylApplication";
    public static IMessage iMessage;
    public static BbylApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        initLogger();
        initNetwork();
        bindMsgService();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    public static BbylApplication getInstance() {
        return mInstance;
    }

    private void initLogger() {
        Logger.addLogAdapter(new AndroidLogAdapter(TAG, false));
        Logger.setLogConverter(new AndroidLogConverter());
    }

    private void bindMsgService() {
        Intent intent = new Intent(this, MsgService.class);
        bindService(intent, msgServiceConn, Context.BIND_IMPORTANT);
        startService(intent);
    }

    private ServiceConnection msgServiceConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Logger.e("onServiceConnected");
            iMessage = IMessage.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Logger.e("onServiceDisconnected");
            if (iMessage != null) {
                iMessage = null;
            }
        }
    };

    void initNetwork() {

    }

}
